<html>
  <head>
    <meta charset="UTF-8">
    <title>Hello World</title>
  </head>
  <body>
    <h1>重建表格内容</h1>
    
    <div id="table-container"></div>
  </body>
  <script>
    // API请求函数，获取info数据
    async function fetchInfo() {
      try {
        // 使用现有的URL作为API端点
        const apiUrl = "https://jiefile.14ku.cn/image_to_execl";
        const response = await fetch(apiUrl, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
            // 如果需要认证，可以添加Authorization头
            // 'Authorization': 'Bearer your-token-here'
          }
        });
        
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const data = await response.json();
        return data;
      } catch (error) {
        console.error('获取info数据失败:', error);
        // 返回默认数据或抛出错误
        throw error;
      }
    }
    
    /**
     * 表格重建函数 - 合并版本
     * 重建表格逻辑：
     * 1、分析cell_box坐标数据，确定表格的行列结构
     * 2、根据y坐标排序确定行顺序，根据x坐标排序确定列顺序
     * 3、为每个单元格设置对应的背景颜色（color属性）
     * 4、在单元格中显示对应的文本内容（cell_text数组中的text属性）
     * 5、样式设置：根据cell_text.box中的数据动态设置表格中文字内容的textAlign属性为左对齐、居中对齐、右对齐
     * 6、单元格合并处理：根据cell_box的坐标范围确定哪些单元格需要合并，设置colspan和rowspan属性
     * 7、表头表尾处理：根据block_bbox动态计算字体大小
     * @param {Object} infoObj - 表格数据对象
     * @returns {HTMLElement} - 重建后的表格元素
     */
    function rebuildTable(infoObj) {
      const tableData = infoObj.data.data;
      
      // 解析table_info数据，根据table_position进行分组
      const tableInfoData = infoObj.data.table_info || [];
      const theadData = tableInfoData.filter(item => item.table_position === 'above_table');
      const tfootData = tableInfoData.filter(item => item.table_position === 'below_table');
      console.log('tfootData', tfootData);
      // 创建表格元素
      const table = document.createElement('table');
      table.style.borderCollapse = 'separate';
      table.style.borderSpacing = '0';
      table.style.marginTop = '20px';
      let  tableSize = null;
      // 解析table_size字段，设置表格尺寸
      if (infoObj.data.table_size) {
        tableSize = infoObj.data.table_size;
        if (tableSize.width) {
          table.style.width = typeof tableSize.width === 'number' ? tableSize.width + 'px' : tableSize.width;
        } else {
          table.style.width = '100%'; // 默认宽度
        }
        if (tableSize.height) {
          table.style.height = typeof tableSize.height === 'number' ? tableSize.height + 'px' : tableSize.height;
        }
      } else {
        table.style.width = '100%'; // 默认宽度
      }
      
      // ========== 数据预处理：去除重复数据 ==========
      const uniqueTableData = [];
      const seenCells = new Set();
      
      // 反向遍历数据，这样最后出现的重复数据会被保留
      const reversedTableData = [...tableData].reverse();
      
      reversedTableData.forEach(cell => {
        const [x1, y1, x2, y2] = cell.cell_box;
        // 创建单元格的唯一标识（基于坐标和内容）
        const cellKey = `${x1.toFixed(2)}_${y1.toFixed(2)}_${x2.toFixed(2)}_${y2.toFixed(2)}`;
        
        // 检查是否是特殊类型单元格（基于位置和文本特征而非硬编码文本）
        const isSpecialCell = cell.cell_text && cell.cell_text.some(text => {
          const textContent = text.text.trim();
          // 基于文本特征判断：短文本（1-3个字符）且位于表格特定位置
          return textContent.length >= 1 && textContent.length <= 3 && 
                 textContent.length === textContent.replace(/[^\u4e00-\u9fa5]/g, '').length; // 纯中文字符
        });
        
        // 检查是否已经存在相似的单元格
        let isDuplicate = false;
        for (const seenKey of seenCells) {
          const [seenX1, seenY1, seenX2, seenY2] = seenKey.split('_').map(Number);
          // 检查坐标是否非常接近（容差为3，严格的去重标准）
          if (Math.abs(x1 - seenX1) < 3 && Math.abs(y1 - seenY1) < 3 && 
              Math.abs(x2 - seenX2) < 3 && Math.abs(y2 - seenY2) < 3) {
            isDuplicate = true;
            if (isSpecialCell) {
              // 特殊类型单元格被标记为重复，跳过处理
            }
            break;
          }
        }
        
        if (!isDuplicate) {
          uniqueTableData.unshift(cell); // 使用unshift保持原始顺序
          seenCells.add(cellKey);
          if (isSpecialCell) {
            // 特殊类型单元格通过去重检查，保留处理
          }
        }
      });
      
      // 统计去重后的特殊类型单元格数据
      const uniqueSpecialData = uniqueTableData.filter(cell => 
        cell.cell_text && cell.cell_text.some(text => {
          const textContent = text.text.trim();
          return textContent.length >= 1 && textContent.length <= 3 && 
                 textContent.length === textContent.replace(/[^\u4e00-\u9fa5]/g, '').length;
        })
      );
      
      // 使用去重后的数据
      const processedTableData = uniqueTableData;
      
      // ========== 坐标分析和分组逻辑 ==========
      const rows = new Set();
      const cols = new Set();
      
      // 收集所有唯一的y坐标（行）和x坐标（列）
      processedTableData.forEach(cell => {
        const [x1, y1, x2, y2] = cell.cell_box;
        rows.add(y1);
        cols.add(x1);
      });
      
      // 转换为数组并排序
      const sortedRows = Array.from(rows).sort((a, b) => a - b);
      const sortedCols = Array.from(cols).sort((a, b) => a - b);
      
      // 将相近的坐标归组（阈值20）
      const groupCoordinates = (coordinates) => {
        if (coordinates.length === 0) return { groups: [], representatives: [] };
        
        const groups = [];
        let currentGroup = [coordinates[0]];
        
        for (let i = 1; i < coordinates.length; i++) {
          if (coordinates[i] - currentGroup[currentGroup.length - 1] < 10) {
            currentGroup.push(coordinates[i]);
          } else {
            groups.push(currentGroup);
            currentGroup = [coordinates[i]];
          }
        }
        groups.push(currentGroup);
        
        return {
          groups: groups,
          representatives: groups.map(group => group[0])
        };
      };
      
      const rowGroups = groupCoordinates(sortedRows);
      const colGroups = groupCoordinates(sortedCols);
      
      const { representativeRows, groupedRows, representativeCols, groupedCols } = {
        representativeRows: rowGroups.representatives,
        groupedRows: rowGroups.groups,
        representativeCols: colGroups.representatives,
        groupedCols: colGroups.groups
      };
      

      
      // ========== 创建表头==========
      if (theadData.length > 0) {
        const thead = table.createTHead();
        
        // 获取表格容器的宽度信息来计算绝对位置
        if (tableSize) {
          const containerWidth = tableSize.width;
          // 计算表格数据的实际宽度和起始位置来确定缩放比例
              const minTableX = Math.min(...processedTableData.map(cell => cell.cell_box[0]));
              const maxTableX = Math.max(...processedTableData.map(cell => cell.cell_box[2]));
          const actualTableWidth = maxTableX - minTableX;
          const scaleRatio = containerWidth / actualTableWidth;
          
          // 计算每列的平均宽度
          const avgColWidth = containerWidth / representativeCols.length;
          
          // 按照y坐标分组表头数据，比较当前文本y1与上一组文本y1差值
          const headerGroups = [];
          
          // 先按y1坐标排序表头数据
          const sortedByY = [...theadData].sort((a, b) => {
            if (a.block_bbox && a.block_bbox.length >= 4 && b.block_bbox && b.block_bbox.length >= 4) {
              return a.block_bbox[1] - b.block_bbox[1];
            }
            return 0;
          });
          
          // 分组逻辑：比较当前文本y1与上一组文本y1差值
          if (sortedByY.length > 0) {
            let currentGroup = [sortedByY[0]];
            let lastGroupY1 = sortedByY[0].block_bbox && sortedByY[0].block_bbox.length >= 4 ? sortedByY[0].block_bbox[1] : null;
            
            for (let i = 1; i < sortedByY.length; i++) {
              const currentItem = sortedByY[i];
              
              if (currentItem.block_bbox && currentItem.block_bbox.length >= 4) {
                const currentY1 = currentItem.block_bbox[1];
                
                // 计算与上一组y1的差值
                const yDiff = Math.abs(currentY1 - lastGroupY1);
                
                // 如果差值大于等于15，则创建新组
                if (yDiff >= 15) {
                  headerGroups.push(currentGroup);
                  currentGroup = [currentItem];
                  lastGroupY1 = currentY1;
                } else {
                  // 否则加入当前组
                  currentGroup.push(currentItem);
                }
              } else {
                // 如果没有block_bbox数据，加入当前组
                currentGroup.push(currentItem);
              }
            }
            // 添加最后一组
            headerGroups.push(currentGroup);
          }
          
          // 为每个组创建表头行
          headerGroups.forEach((group, groupIndex) => {
            const theadRow = thead.insertRow();
            
            // 按照x坐标排序当前组的表头数据
            const sortedGroup = [...group].sort((a, b) => {
              if (a.block_bbox && a.block_bbox.length >= 4 && b.block_bbox && b.block_bbox.length >= 4) {
                return a.block_bbox[0] - b.block_bbox[0];
              }
              return 0;
            });
            
            let currentCol = 0;
            sortedGroup.forEach(item => {
              // 根据block_bbox确定文本位置和列跨度
              if (item.block_bbox && item.block_bbox.length >= 4) {
                const [x1, y1, x2, y2] = item.block_bbox;
                
                // 计算表头应该跨越的列数
                const headerWidth = x2 - x1;
                const scaledHeaderWidth = headerWidth * scaleRatio;
                
                // 计算应该跨越的列数
                const colSpan = Math.max(1, Math.min(representativeCols.length - currentCol, Math.round(scaledHeaderWidth / avgColWidth)));
                
                // 计算从哪一列开始
                const relativeOffset = Math.max(0, x1 - minTableX);
                const scaledOffset = relativeOffset * scaleRatio;
                const startCol = Math.min(representativeCols.length - 1, Math.floor(scaledOffset / avgColWidth));
                
                // 填充空白单元格
                while (currentCol < startCol) {
                  const emptyCell = theadRow.insertCell();
                  emptyCell.style.backgroundColor = '#f5f5f5';
                  emptyCell.style.border = 'none';
                  currentCol++;
                }
                
                // 创建表头单元格
                const th = document.createElement('th');
                th.colSpan = colSpan;
                th.style.backgroundColor = '#f5f5f5';
                th.style.fontWeight = 'bold';
                th.style.textAlign = 'center';
                
                // 只在最后一组表头显示底部边框
                if (groupIndex === headerGroups.length - 1) {
                  th.style.borderBottom = '2px solid #ddd';
                } else {
                  th.style.borderBottom = 'none';
                }
            
                // 根据block_bbox计算字体大小
                if (item.block_bbox && item.block_bbox.length >= 4) {
                  const [x1, y1, x2, y2] = item.block_bbox;
                  const bboxHeight = y2 - y1;
                  
                  // 根据bbox高度计算字体大小，通常字体大小为高度的60-80%
                  let fontSize;
                  if (item.block_label === 'figure_title') {
                    // 表头主题内容使用较大的比例
                    fontSize = Math.max(16, Math.min(24, bboxHeight * 0.7));
                    th.style.color = '#333';
                  } else {
                    // 其他内容使用较小的比例
                    fontSize = Math.max(12, Math.min(18, bboxHeight * 0.6));
                    th.style.color = '#666';
                  }
                  
                  th.style.fontSize = fontSize + 'px';
                } else {
                  // 如果没有block_bbox数据，使用默认字体大小
                  if (item.block_label === 'figure_title') {
                    th.style.fontSize = '18px';
                    th.style.color = '#333';
                  } else {
                    th.style.fontSize = '14px';
                    th.style.color = '#666';
                  }
                }
                
                th.textContent = item.block_content;
                theadRow.appendChild(th);
                
                // 更新当前列位置
                currentCol += colSpan;
              }
            });
            
            // 填充剩余的空白单元格
            while (currentCol < representativeCols.length) {
              const emptyCell = theadRow.insertCell();
              emptyCell.style.backgroundColor = '#f5f5f5';
              emptyCell.style.border = 'none';
              currentCol++;
            }
          });
        }
      }
      
      // ========== 创建单元格占用矩阵和表格主体 ==========
      const cellMatrix = Array(representativeRows.length).fill(null).map(() => 
        Array(representativeCols.length).fill(false)
      );
      
      // 创建tbody元素
      const tbody = table.createTBody();
      
      // 创建行
      representativeRows.forEach((rowY, rowIndex) => {
        const row = tbody.insertRow();
        const currentRowGroup = groupedRows[rowIndex];
          // 创建列
        representativeCols.forEach((colX, colIndex) => {
          
          // 如果当前位置已被占用，则跳过
          if (cellMatrix[rowIndex][colIndex]) {
            return;
          }
          // 使用动态容差值来处理重复数据，根据表格密度调整容差
          const tableDensity = processedTableData.length / (representativeRows.length * representativeCols.length);
          const dynamicTolerance = Math.max(5, Math.min(25, 15 * (1 + tableDensity * 0.5)));
          
          // 查找对应的单元格数据 - 性能优化：使用哈希表减少线性搜索
          const currentColGroup = groupedCols[colIndex];
          let matchingCell = null;
          
          // 性能优化：只搜索可能匹配的单元格，避免全表扫描
          for (let i = 0; i < processedTableData.length; i++) {
            const data = processedTableData[i];
            const [x1, y1, x2, y2] = data.cell_box;
            
            // 快速预检查：如果y坐标差异过大，直接跳过
            const yDiff = Math.abs(y1 - rowY);
            if (yDiff >= 20) continue; // 预检查阈值
            
            const xMatch = currentColGroup.some(groupX => Math.abs(x1 - groupX) < dynamicTolerance);
            const yMatch = Math.abs(y1 - rowY) < dynamicTolerance;
            
            if (xMatch && yMatch) {
              matchingCell = data;
              break; // 找到匹配后立即退出循环
            }
          }
          
          if (matchingCell) {
            const [cellX1, cellY1, cellX2, cellY2] = matchingCell.cell_box;
            
            const isTitleCell = matchingCell.cell_text && matchingCell.cell_text.some(text => 
              text.text.includes('表') || text.text.includes('标题') || text.text.includes('分析')
            );
            
            // ========== 计算单元格合并范围（性能优化版） ==========
            let colspan = 1;
            let rowspan = 1;
            
            // 性能优化：缓存计算结果，避免重复计算
            const cellWidth = cellX2 - cellX1;
            const cellHeight = cellY2 - cellY1;
            
            // 计算colspan：检查当前单元格覆盖了多少列
            
            for (let i = colIndex + 1; i < representativeCols.length; i++) {
              const nextColX = representativeCols[i];
              
              // 性能优化：如果下一列x坐标超出当前单元格范围，立即终止
              if (nextColX >= cellX2) break;
              
              // 检查下一列是否真的有匹配的单元格数据
              let hasMatchingCellInNextCol = false;
              for (let k = 0; k < processedTableData.length; k++) {
                const nextCellData = processedTableData[k];
                const [nextCellX1, nextCellY1, nextCellX2, nextCellY2] = nextCellData.cell_box;
                
                // 检查是否在下一列的x坐标范围内，使用动态容差
                const xMatch = Math.abs(nextCellX1 - nextColX) < dynamicTolerance;
                
                // 检查是否在当前单元格的y坐标范围内，使用动态容差
                const yMatch = Math.abs(nextCellY1 - cellY1) < cellHeight + dynamicTolerance;
                
                if (xMatch && yMatch) {
                  hasMatchingCellInNextCol = true;
                  break;
                }
              }
              
              // 如果下一列的x坐标在当前单元格的x范围内，并且有匹配的单元格数据，则属于同一合并单元格
              // 基于cell_box坐标数据判断是否需要跨列
              
              // 计算当前单元格的实际宽度和期望的列数
              const actualCellWidth = cellX2 - cellX1;
              
              // 计算平均列宽（基于representativeCols）
              let avgColWidth = 0;
              if (representativeCols.length > 1) {
                const totalWidth = representativeCols[representativeCols.length - 1] - representativeCols[0];
                avgColWidth = totalWidth / (representativeCols.length - 1);
              }
              
              // 如果单元格实际宽度明显大于平均列宽，则应该跨列
              const expectedColspan = Math.round(actualCellWidth / avgColWidth);
              const shouldSpanMultipleCols = expectedColspan > 1 && actualCellWidth > avgColWidth * 1.1;
              
              // 对于标题单元格，保持原有的宽松距离检查
              const isTitleCell = matchingCell.cell_text && matchingCell.cell_text.some(text => 
                text.text.includes('表') || text.text.includes('标题') || text.text.includes('分析')
              );
              
              const distanceThreshold = (isTitleCell || shouldSpanMultipleCols) ? cellWidth * 1.5 : cellWidth;
              const distanceCheck = Math.abs(nextColX - cellX1) < distanceThreshold;
              

              
              // 对于标题单元格或需要跨列的单元格，如果距离检查通过但没有匹配的单元格数据，也允许合并
              if (distanceCheck && (hasMatchingCellInNextCol || isTitleCell || shouldSpanMultipleCols)) {
                colspan++;
                // 标记这些位置为已占用
                cellMatrix[rowIndex][i] = true;
              } else {

                break;
              }
            }
            

            
            // 计算rowspan：检查当前单元格覆盖了多少行
            for (let i = rowIndex + 1; i < representativeRows.length; i++) {
              const nextRowY = representativeRows[i];
              
              // 性能优化：如果下一行y坐标超出当前单元格范围，立即终止
              if (nextRowY >= cellY2) break;
              
              // 检查下一行是否真的有匹配的单元格数据
              let hasMatchingCellInNextRow = false;
              for (let k = 0; k < processedTableData.length; k++) {
                const nextCellData = processedTableData[k];
                const [nextCellX1, nextCellY1, nextCellX2, nextCellY2] = nextCellData.cell_box;
                
                // 检查是否在下一行的y坐标范围内，使用动态容差
                const yMatch = Math.abs(nextCellY1 - nextRowY) < dynamicTolerance;
                
                // 检查是否在当前单元格的x坐标范围内（考虑colspan），使用动态容差
                const xMatch = Math.abs(nextCellX1 - cellX1) < cellWidth * colspan + dynamicTolerance;
                
                if (yMatch && xMatch) {
                  hasMatchingCellInNextRow = true;
                  break;
                }
              }
              
              // 如果下一行的y坐标在当前单元格的y范围内，并且有匹配的单元格数据，则属于同一合并单元格
              
              if (Math.abs(nextRowY - cellY1) < cellHeight && hasMatchingCellInNextRow) {
                // 检查下一行是否包含与当前单元格相同的数据（用于跨行单元格）
                let isSameCellData = false;
                for (let k = 0; k < processedTableData.length; k++) {
                  const nextCellData = processedTableData[k];
                  const [nextCellX1, nextCellY1, nextCellX2, nextCellY2] = nextCellData.cell_box;
                  
                  // 检查是否在下一行的y坐标范围内，使用动态容差
                  const yMatch = Math.abs(nextCellY1 - nextRowY) < dynamicTolerance;
                  
                  // 检查是否在当前单元格的x坐标范围内（考虑colspan），使用动态容差
                  const xMatch = Math.abs(nextCellX1 - cellX1) < cellWidth * colspan + dynamicTolerance;
                  
                  // 检查是否是相同的单元格数据（通过坐标范围判断）
                  if (yMatch && xMatch && 
                      Math.abs(nextCellX1 - cellX1) < dynamicTolerance && 
                      Math.abs(nextCellX2 - cellX2) < dynamicTolerance) {
                    isSameCellData = true;
                    break;
                  }
                }
                
                // 如果是相同单元格数据或者是真正的跨行单元格，则增加rowspan
                if (isSameCellData || Math.abs(nextRowY - cellY1) < cellHeight * 0.8) {
                  rowspan++;
                  // 标记这些位置为已占用
                  cellMatrix[i][colIndex] = true;
                  // 如果colspan > 1，也需要标记合并列的位置
                  for (let j = 1; j < colspan; j++) {
                    cellMatrix[i][colIndex + j] = true;
                  }
                } else {
                  // 如果不是相同单元格数据，停止rowspan计算
                  break;
                }
              } else {
                break;
              }
            }
            
            const cell = row.insertCell();
            cell.style.border = '1px solid #ddd';
            cell.style.boxSizing = 'border-box';
            cell.style.textAlign = 'center';
            cell.style.verticalAlign = 'middle';
            
            // 设置单元格宽度和高度
            if (matchingCell.cell_box && matchingCell.cell_box.length >= 4) {
              const [cellX1, cellY1, cellX2, cellY2] = matchingCell.cell_box;
              const cellWidth = cellX2 - cellX1;
              const cellHeight = cellY2 - cellY1;
              cell.style.width = cellWidth  + 'px';
              cell.style.height = cellHeight + 'px';
            }
            
            // 设置colspan和rowspan
            if (colspan > 1) {
              cell.colSpan = colspan;
            }
            if (rowspan > 1) {
              cell.rowSpan = rowspan;
            }
            
            // 设置单元格背景色
            if (matchingCell.color && matchingCell.color.trim() !== '') {
              cell.style.backgroundColor = matchingCell.color;
            } else {
              // 如果没有color属性或为空，使用默认背景色
              cell.style.backgroundColor = '#ffffff';
            }
            
            // ========== 添加文本内容==========
            if (matchingCell.cell_text && matchingCell.cell_text.length > 0) {
              const textDiv = document.createElement('div');
              
              // 计算同一单元格中统一的字体大小）
              let unifiedFontSize = 14; // 默认字体大小
              // const validTextItems = matchingCell.cell_text.filter(item => item.box && item.box.length >= 4);
              
              // if (validTextItems.length > 0) {
              //   // 计算所有文本的平均高度，然后确定统一的字体大小
              //   const avgTextHeight = validTextItems.reduce((sum, item) => {
              //     const [textX1, textY1, textX2, textY2] = item.box;
              //     return sum + (textY2 - textY1);
              //   }, 0) / validTextItems.length;
                
              //   // 使用平均文本高度的65%作为统一字体大小，并设置限制
              //   unifiedFontSize = Math.max(12, Math.min(24, avgTextHeight * 0.65));
              // }
              
              // 性能优化：根据box的y坐标对文本进行分组，判断是否在同一行（优化版）
              const textGroups = [];
              const processedTexts = new Set();
              
              // 性能优化：预先计算所有文本的y坐标，避免重复访问
              const textYCoords = matchingCell.cell_text.map((item, index) => {
                if (item.box && item.box.length >= 4) {
                  return { y: item.box[1], index, height: item.box[3] - item.box[1] };
                }
                return null;
              }).filter(item => item !== null);
              
              // 性能优化：按y坐标排序，减少分组时的搜索范围
              textYCoords.sort((a, b) => a.y - b.y);
              
              textYCoords.forEach(({ y: currentY, index: currentIndex, height: currentHeight }) => {
                if (processedTexts.has(currentIndex)) return;
                
                const currentGroup = [matchingCell.cell_text[currentIndex]];
                processedTexts.add(currentIndex);
                
                // 性能优化：只检查后续的文本，利用已排序的特性
                for (let i = textYCoords.findIndex(item => item.index === currentIndex) + 1; i < textYCoords.length; i++) {
                  const { y: otherY, index: otherIndex } = textYCoords[i];
                  
                  if (processedTexts.has(otherIndex)) continue;
                  
                  // 判断是否在同一行：y坐标相差小于文本高度的50%
                  const yDiff = Math.abs(currentY - otherY);
                  
                  if (yDiff < currentHeight * 0.5) {
                    currentGroup.push(matchingCell.cell_text[otherIndex]);
                    processedTexts.add(otherIndex);
                  } else if (otherY > currentY + currentHeight * 0.5) {
                    // 性能优化：由于已排序，后续文本y坐标更大，可以直接终止
                    break;
                  }
                }
                
                textGroups.push(currentGroup);
              });
              
              // 为每一行文本创建一个容器
              textGroups.forEach(group => {
                const rowDiv = document.createElement('div');
                rowDiv.style.display = 'flex';
                rowDiv.style.padding = '0px 2px';
                
                // 设置对齐方式
                if (group.length >= 2 && group.every(item => item.box && item.box.length >= 4)) {
                  // 获取所有文本的x坐标
                  const xPositions = group.map(item => item.box[0]);
                  const minX = Math.min(...xPositions);
                  const maxX = Math.max(...xPositions);
                  
                  // 计算文本分布范围
                  const textRange = maxX - minX;
                  const avgTextWidth = group.reduce((sum, item) => sum + (item.box[2] - item.box[0]), 0) / group.length;
                  
                  // 如果文本分布范围大于平均文本宽度的1.5倍，说明文本分布在两端，使用space-between
                  if (textRange > avgTextWidth * 1.2) {
                    rowDiv.style.alignItems = 'center';
                    rowDiv.style.justifyContent = 'space-around';
                  } else {
                    // 文本集中在中间，使用center
                    rowDiv.style.alignItems = 'center';
                    rowDiv.style.justifyContent = 'center';
                  }
                } else {
                  // 单个文本，根据文本在单元格中的位置设置对齐方式
                  if (group.length === 1 && group[0].box && group[0].box.length >= 4 && matchingCell.cell_box) {
                    const [textX1, textY1, textX2, textY2] = group[0].box;
                    const [cellX1, cellY1, cellX2, cellY2] = matchingCell.cell_box;
                    
                    // 计算文本在单元格中的相对位置
                    const cellWidth = cellX2 - cellX1;
                    const textWidth = textX2 - textX1;
                    const textRelativeX = textX1 - cellX1;
                    
                    // 计算文本中心在单元格中的相对位置比例 (0-1)
                    const textCenterRatio = (textRelativeX + textWidth / 2) / cellWidth;
                    
                    if (textCenterRatio < 0.33) {
                      // 文本偏向左侧，使用左对齐
                      rowDiv.style.alignItems = 'center';
                      rowDiv.style.justifyContent = 'flex-start';
                    } else if (textCenterRatio > 0.67) {
                      // 文本偏向右侧，使用右对齐
                      rowDiv.style.alignItems = 'center';
                      rowDiv.style.justifyContent = 'flex-end';
                    } else {
                      // 文本在中间区域，使用居中对齐
                      rowDiv.style.alignItems = 'center';
                      rowDiv.style.justifyContent = 'center';
                    }
                  } else {
                    // 数据不完整，默认使用center
                    rowDiv.style.alignItems = 'center';
                    rowDiv.style.justifyContent = 'center';
                  }
                }
                
                // 对同一行的文本按x坐标排序
                group.sort((a, b) => {
                  if (a.box && a.box.length >= 4 && b.box && b.box.length >= 4) {
                    return a.box[0] - b.box[0];
                  }
                  return 0;
                });
                
                // 为每个文本片段创建span元素（原createTextSpan函数）
                group.forEach(textItem => {
                  const textSpan = document.createElement('span');
                  textSpan.textContent = textItem.text;
                  // textSpan.style.marginRight = '8px';
                  
                  // 根据direction字段设置文字方向
                  if (textItem.direction === 'vertical') {
                    textSpan.style.writingMode = 'vertical-rl';
                    textSpan.style.textOrientation = 'mixed';
                    // 垂直文字时调整margin
                    textSpan.style.marginRight = '0px';
                    textSpan.style.marginBottom = '8px';
                  }
                  
                  // 根据cell_text.box数据动态设置textAlign，使用统一的fontSize
                  if (textItem.box && textItem.box.length >= 4) {
                    const [textX1, textY1, textX2, textY2] = textItem.box;
                    const [cellX1, cellY1, cellX2, cellY2] = matchingCell.cell_box;
                    
                    // 计算文本在单元格中的相对位置
                    const cellWidth = cellX2 - cellX1;
                    const textWidth = textX2 - textX1;
                    const textHeight = textY2 - textY1;
                    const textRelativeX = textX1 - cellX1;
                    
                    // 优化字体大小计算策略：
                    // 1. 计算单元格中所有文本的平均高度
                    const textHeights = matchingCell.cell_text
                      .filter(t => t.box && t.box.length >= 4)
                      .map(t => t.box[3] - t.box[1]);
                    const avgTextHeight = textHeights.length > 0 
                      ? textHeights.reduce((sum, h) => sum + h, 0) / textHeights.length 
                      : textHeight;
                    
                    // 2. 使用平滑的字体大小计算，基于平均文本高度
                    // 限制在12-24px范围内，使用65%的比例，并添加0.5px的平滑处理
                    unifiedFontSize = Math.max(12, Math.min(24, Math.round(avgTextHeight * 0.65 * 2) / 2));
                    
                    // 3. 使用统一的字体大小
                    textSpan.style.fontSize = '16px';
                  }
                  
                  rowDiv.appendChild(textSpan);
                  rowDiv.style.height = unifiedFontSize*1.5 + 'px';
                });
                
                textDiv.appendChild(rowDiv);
              });
              
              cell.appendChild(textDiv);
            }
          } else {
            // 如果没有找到对应的单元格数据，创建一个空单元格
            const cell = row.insertCell();
            cell.style.border = '1px solid #ddd';
            cell.style.textAlign = 'center';
            
            // 为空单元格设置默认宽度和高度
            cell.style.width = '100px';
            cell.style.height = '40px';
          }
        });
      });
      
      // ========== 创建表尾（修复below_table数据显示） ==========
      if (tfootData.length > 0) {
        const tfoot = table.createTFoot();
        
        // 合并所有below_table内容
        const belowTableContent = tfootData
          .filter(item => item.table_position === 'below_table')
          .map(item => item.block_content)
          .join('\n');
        
        if (belowTableContent) {
          const tfootRow = tfoot.insertRow();
          const td = document.createElement('td');
          td.colSpan = representativeCols.length;
          td.style.backgroundColor = '#f8f9fa';
          td.style.borderTop = '2px solid #ddd';
          td.style.borderBottom = '2px solid #ddd';
          td.style.color = '#333';
          td.style.lineHeight = '1.6';
          td.style.padding = '12px 8px';
          td.style.fontSize = '14px';
          td.style.textAlign = 'left';
          
          // 处理多行文本
          const lines = belowTableContent.split('\n').filter(line => line.trim());
          lines.forEach(line => {
            const p = document.createElement('p');
            p.textContent = line.trim();
            p.style.margin = '4px 0';
            p.style.lineHeight = '1.5';
            td.appendChild(p);
          });
          
          tfootRow.appendChild(td);
        }
      }
      return table;
    }


    
    // 页面加载完成后重建表格
    window.addEventListener('load', async function() {
      const tableContainer = document.getElementById('table-container');
      try {
        // 尝试从API获取数据
        // const apiData = await fetchInfo();  
        const  dataStr = `{"code":0,"data":{"data":[{"cell_box":[3.497159957885742,69.2030577659607,112.65291595458984,112.65291595458984],"cell_text":[],"color":"#fbfdfd"},{"cell_box":[112.65291595458984,69.2030577659607,316.52899169921875,112.65291595458984],"cell_text":[{"box":[169,80,220,102],"direction":"horizontal","text":"星期一"}],"color":"#93ebaf"},{"cell_box":[316.52899169921875,69.2030577659607,552.8572387695312,112.65291595458984],"cell_text":[{"box":[405,80,457,102],"direction":"horizontal","text":"星期二"}],"color":"#b7cefa"},{"cell_box":[552.8572387695312,69.2030577659607,788.0346069335938,112.65291595458984],"cell_text":[{"box":[642,80,695,101],"direction":"horizontal","text":"星期三"}],"color":"#fcdd1b"},{"cell_box":[788.0346069335938,69.2030577659607,1028.8408203125,112.65291595458984],"cell_text":[{"box":[880,80,932,102],"direction":"horizontal","text":"星期四"}],"color":"#fbbd3b"},{"cell_box":[1028.8408203125,69.2030577659607,1256.37939453125,112.65291595458984],"cell_text":[{"box":[1115,79,1170,104],"direction":"horizontal","text":"星期五"}],"color":"#fdac81"},{"cell_box":[3.497159957885742,112.65291595458984,112.65291595458984,225.28811645507812],"cell_text":[{"box":[29,174,67,197],"direction":"horizontal","text":"早餐"}],"color":"#fcfefe"},{"cell_box":[112.65291595458984,112.65291595458984,316.52899169921875,225.28811645507812],"cell_text":[{"box":[157,133,231,154],"direction":"horizontal","text":"大米苹果粥"},{"box":[158,162,231,182],"direction":"horizontal","text":"香芹玉米粒"},{"box":[163,190,225,212],"direction":"horizontal","text":"鲜奶馒头"}],"color":"#f0fdf3"},{"cell_box":[316.52899169921875,112.65291595458984,552.8572387695312,225.28811645507812],"cell_text":[{"box":[401,147,461,167],"direction":"horizontal","text":"煮鹌鹑蛋"},{"box":[401,174,461,195],"direction":"horizontal","text":"红枣豆浆"}],"color":"#f0fdf1"},{"cell_box":[552.8572387695312,112.65291595458984,788.0346069335938,225.28811645507812],"cell_text":[{"box":[645,134,691,153],"direction":"horizontal","text":"鸡蛋美"},{"box":[644,161,692,182],"direction":"horizontal","text":"蝴蝶卷"},{"box":[639,192,698,210],"direction":"horizontal","text":"酱香豆干"}],"color":"#f0fdf1"},{"cell_box":[788.0346069335938,112.65291595458984,1028.8408203125,225.28811645507812],"cell_text":[{"box":[858,149,953,166],"direction":"horizontal","text":"牛奶鸡蛋燕麦片"},{"box":[864,177,948,195],"direction":"horizontal","text":"蜂宝南瓜蛋糕"}],"color":"#f0fdf1"},{"cell_box":[1028.8408203125,112.65291595458984,1244.444091796875,225.28811645507812],"cell_text":[{"box":[1111,132,1172,153],"direction":"horizontal","text":"五谷豆浆"},{"box":[1118,161,1167,183],"direction":"horizontal","text":"荷叶饼"},{"box":[1106,192,1178,210],"direction":"horizontal","text":"彩椒土豆丝"}],"color":"#f0fdf1"},{"cell_box":[3.497159957885742,225.28811645507812,112.65291595458984,316.52899169921875],"cell_text":[{"box":[28,275,69,298],"direction":"horizontal","text":"早点"}],"color":"#fafcfc"},{"cell_box":[112.65291595458984,225.28811645507812,316.52899169921875,316.52899169921875],"cell_text":[{"box":[176,248,212,271],"direction":"horizontal","text":"甜瓜"},{"box":[170,277,218,299],"direction":"horizontal","text":"葡萄干"}],"color":"#eaf9fd"},{"cell_box":[316.52899169921875,225.28811645507812,552.8572387695312,316.52899169921875],"cell_text":[{"box":[415,250,447,269],"direction":"horizontal","text":"香蕉"},{"box":[408,278,454,297],"direction":"horizontal","text":"大杏仁"}],"color":"#eaf9fd"},{"cell_box":[552.8572387695312,225.28811645507812,788.0346069335938,316.52899169921875],"cell_text":[{"box":[645,250,691,269],"direction":"horizontal","text":"圣女果"},{"box":[645,278,692,297],"direction":"horizontal","text":"山植卷"}],"color":"#e9f9ff"},{"cell_box":[788.0346069335938,225.28811645507812,1028.8408203125,316.52899169921875],"cell_text":[{"box":[887,248,924,271],"direction":"horizontal","text":"西瓜"},{"box":[882,278,929,297],"direction":"horizontal","text":"小饼干"}],"color":"#e9f9ff"},{"cell_box":[1028.8408203125,225.28811645507812,1244.444091796875,316.52899169921875],"cell_text":[{"box":[1123,248,1162,271],"direction":"horizontal","text":"苹果"},{"box":[1118,276,1167,299],"direction":"horizontal","text":"威化饼"}],"color":"#e9f9ff"},{"cell_box":[3.497159957885742,316.52899169921875,112.65291595458984,459.2012634277344],"cell_text":[{"box":[28,389,68,418],"direction":"horizontal","text":"午餐"}],"color":"#fcfefe"},{"cell_box":[112.65291595458984,316.52899169921875,316.52899169921875,459.2012634277344],"cell_text":[{"box":[164,336,225,357],"direction":"horizontal","text":"金银米饭"},{"box":[151,365,237,385],"direction":"horizontal","text":"胡萝卜焖牛腩"},{"box":[170,393,219,415],"direction":"horizontal","text":"丝瓜汤"},{"box":[157,423,231,444],"direction":"horizontal","text":"孜然土豆片"}],"color":"#fdf7f2"},{"cell_box":[316.52899169921875,316.52899169921875,552.8572387695312,459.2012634277344],"cell_text":[{"box":[401,364,460,384],"direction":"horizontal","text":"牛肉焖面"},{"box":[395,393,467,414],"direction":"horizontal","text":"紫菜虾皮汤"}],"color":"#fcf6f1"},{"cell_box":[552.8572387695312,316.52899169921875,788.0346069335938,459.2012634277344],"cell_text":[{"box":[638,337,698,355],"direction":"horizontal","text":"燕麦米饭"},{"box":[638,365,699,385],"direction":"horizontal","text":"咖喱鸡块"},{"box":[631,393,704,414],"direction":"horizontal","text":"豌豆炒三丁"},{"box":[627,424,710,442],"direction":"horizontal","text":"西红柿鸡蛋汤"}],"color":"#fdf7f2"},{"cell_box":[788.0346069335938,316.52899169921875,1028.8408203125,459.2012634277344],"cell_text":[{"box":[870,364,941,386],"direction":"horizontal","text":"柳叶鸡丝面"},{"box":[876,393,936,414],"direction":"horizontal","text":"粉丝菠菜"}],"color":"#fcf6f1"},{"cell_box":[1028.8408203125,316.52899169921875,1244.444091796875,459.2012634277344],"cell_text":[{"box":[1119,336,1168,358],"direction":"horizontal","text":"香米饭"},{"box":[1099,364,1186,387],"direction":"horizontal","text":"什锦炒鸡肉丁"},{"box":[1100,393,1186,414],"direction":"horizontal","text":"瑶柱极品豆腐"},{"box":[1106,423,1180,444],"direction":"horizontal","text":"冬瓜香菇汤"}],"color":"#fdf7f2"},{"cell_box":[3.497159957885742,459.2012634277344,112.65291595458984,552.8572387695312],"cell_text":[{"box":[25,505,71,535],"direction":"horizontal","text":"午点"}],"color":"#fcfcfc"},{"cell_box":[112.65291595458984,459.2012634277344,316.52899169921875,552.8572387695312],"cell_text":[{"box":[158,482,231,502],"direction":"horizontal","text":"雪梨银耳美"},{"box":[164,509,223,530],"direction":"horizontal","text":"自制桃酥"}],"color":"#fcf5ec"},{"cell_box":[316.52899169921875,459.2012634277344,552.8572387695312,552.8572387695312],"cell_text":[{"box":[395,482,467,502],"direction":"horizontal","text":"什锦水果美"},{"box":[408,511,454,530],"direction":"horizontal","text":"玉米棒"}],"color":"#fcf4e9"},{"cell_box":[552.8572387695312,459.2012634277344,788.0346069335938,552.8572387695312],"cell_text":[{"box":[651,482,686,501],"direction":"horizontal","text":"酸奶"},{"box":[632,510,705,531],"direction":"horizontal","text":"双色甜发糕"}],"color":"#fcf4e9"},{"cell_box":[788.0346069335938,459.2012634277344,1028.8408203125,552.8572387695312],"cell_text":[{"box":[863,496,948,517],"direction":"horizontal","text":"枸杞醪糟汤圆"}],"color":"#fcf4e9"},{"cell_box":[1028.8408203125,459.2012634277344,1244.444091796875,552.8572387695312],"cell_text":[{"box":[1124,481,1162,503],"direction":"horizontal","text":"酸奶"},{"box":[1113,510,1173,532],"direction":"horizontal","text":"牛角面包"}],"color":"#fcf4e9"},{"cell_box":[3.497159957885742,552.8572387695312,112.65291595458984,694.2485046386719],"cell_text":[{"box":[28,624,67,647],"direction":"horizontal","text":"晚餐"}],"color":"#fcfcfc"},{"cell_box":[112.65291595458984,552.8572387695312,316.52899169921875,694.2485046386719],"cell_text":[{"box":[159,598,230,618],"direction":"horizontal","text":"肉丝烧面条"},{"box":[157,624,230,648],"direction":"horizontal","text":"虾皮小白菜"}],"color":"#fceedf"},{"cell_box":[316.52899169921875,552.8572387695312,552.8572387695312,694.2485046386719],"cell_text":[{"box":[407,568,455,590],"direction":"horizontal","text":"香米饭"},{"box":[394,595,467,619],"direction":"horizontal","text":"红烧鸡翅根"},{"box":[400,626,461,647],"direction":"horizontal","text":"清香蒿"},{"box":[395,656,467,677],"direction":"horizontal","text":"青瓜鸡蛋汤"}],"color":"#feeedf"},{"cell_box":[552.8572387695312,552.8572387695312,788.0346069335938,694.2485046386719],"cell_text":[{"box":[631,595,704,619],"direction":"horizontal","text":"葱油小揪面"},{"box":[633,628,703,646],"direction":"horizontal","text":"豆干圆白菜"}],"color":"#fceedf"},{"cell_box":[788.0346069335938,552.8572387695312,1028.8408203125,694.2485046386719],"cell_text":[{"box":[882,568,930,590],"direction":"horizontal","text":"香米饭"},{"box":[869,598,943,618],"direction":"horizontal","text":"西芹炒木耳"},{"box":[869,626,942,647],"direction":"horizontal","text":"菜花炒肉片"},{"box":[869,656,942,677],"direction":"horizontal","text":"香菇海带汤"}],"color":"#fceedf"},{"cell_box":[1028.8408203125,552.8572387695312,1244.444091796875,694.2485046386719],"cell_text":[{"box":[1106,598,1179,618],"direction":"horizontal","text":"肉丁打卤面"},{"box":[1101,628,1185,646],"direction":"horizontal","text":"油菜干叶豆腐"}],"color":"#fceedf"}],"file_name":"81efc11750894c87978da34a348af411","table_info":[{"block_bbox":[445,33,828,53],"block_content":"宁夏陈老师幼儿园（2023/06/12~2023/06/18）","block_label":"figure_title","table_position":"above_table"},{"block_bbox":[0,66,1279,694],"block_content":"","block_label":"table","table_position":"table"},{"block_bbox":[33,708,127,726],"block_content":"带量营养食谱","block_label":"paragraph_title","table_position":"below_table"},{"block_bbox":[29,732,1106,748],"block_content":"本食谱以幼儿营养工作为重点，在主副食的选料、洗涤，切配、烹调的过程中，方法科学合理，多种食物均衡搭配，达到了营养譜食的要求，园所特意为幼儿设计了花样多变的美食，色，香、味俱全，宝宝们十分喜爱","block_label":"text","table_position":"below_table"}],"table_size":{"height":761,"width":1280}},"msg":"成功"}`
        const apiData = JSON.parse(dataStr);
        const table = rebuildTable(apiData);
        tableContainer.appendChild(table);
      } catch (error) {
        console.warn('API请求失败，使用备用数据:', error);
      }
    });

  </script>

</html>